<?php

/**
 * Mediad co,ltd
 *
 * @category   Mediad
 * @package    Mediad2_Controller_Plugin
 * @subpackage Acl
 * @copyright  Copyright (c) 2012 Mediad co,ltd. (http://www.Mediad.cn)
 * @license    New BSD License
 * @version    $Id: Acl.php 1 2012-03-12 16:19:00Z tany@Mediad.cn $
 */
class Mediad2_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
{
    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        //验证权限，如果没有登录则以游客身份登录
        $auth = Zend_Registry::get('auth');
        if (!$auth->hasIdentity()) {
        	$user = new Mediad2_Model_User();
        	$user->setNickname('游客');
			$user->setRolecode('guest');
        	$auth->getStorage()->write($user);
        }

        //get variables
        $moduleName = $request->getModuleName();
        $controller = $request->getControllerName();
        $action = $request->getActionName();
        //set variables
        $resource = $moduleName.'_'.$controller;                
        $privilege = $action;
		$roleCode = $auth->getIdentity()->getRoleCode();      
		        
        //获取Acl实例
        $acl = Zend_Registry::get('acl');
        
       try {      
       	
	        //判断是否具备访问权限
	        if(!$acl->isAllowed($roleCode, $resource, $privilege)) {
	        	//没有权限，则跳转到错误处理页面       
	        	$session = new Zend_Session_Namespace('Mediad');
	        	$session->errorMessage = "没有权限";
	        	
	        	$request->setModuleName('admin')
	        			->setControllerName('error')
	        			->setActionName('index');
	        }
        
       } catch(Exception $e) {
       	       		
	       	//TODO 发送异常到系统邮箱，返回登录页面
	       	$registry = Zend_Registry::getInstance ();
	       	$mConfig = $registry->mailConfig;
	       	$email=new Mediad2_Service_Util_Email($mConfig);
	       	$email->sendException($e->getMessage());
       }

    }
    
}

